package edu.fudan.dao.hibernate;

import edu.fudan.dao.MeetingRoomDao;
import edu.fudan.model.MeetingRoom;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import javax.persistence.Table;
import java.util.List;

/**
 * This class interacts with Spring's HibernateTemplate to save/delete and
 * retrieve User objects.
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 *   Modified by <a href="mailto:dan@getrolling.com">Dan Kibler</a>
 *   Extended to implement Acegi UserDetailsService interface by David Carter david@carter.net
 *   Modified by <a href="mailto:bwnoll@gmail.com">Bryan Noll</a> to work with 
 *   the new BaseDaoHibernate implementation that uses generics.
*/
@Repository("meetingRoomDao")
public class MeetingRoomDaoHibernate extends GenericDaoHibernate<MeetingRoom, Long> implements MeetingRoomDao {

    /**
     * Constructor that sets the entity to User.class.
     */
    public MeetingRoomDaoHibernate() {
        super(MeetingRoom.class);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<MeetingRoom> getMeetingRooms() {
        return getHibernateTemplate().find("from MeetingRoom mr order by upper(mr.name)");
    }

    /**
     * {@inheritDoc}
     */
    public MeetingRoom saveMeetingRoom(MeetingRoom meetingRoom) {
        if (log.isDebugEnabled()) {
            log.debug("Meeting Room id: " + meetingRoom.getId());
        }
        getHibernateTemplate().saveOrUpdate(meetingRoom);
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        getHibernateTemplate().flush();
        return meetingRoom;
    }

    /**
     * Overridden simply to call the saveUser method. This is happenening 
     * because saveUser flushes the session and saveObject of BaseDaoHibernate 
     * does not.
     *
     * @param user the user to save
     * @return the modified user (with a primary key set if they're new)
     */
    @Override
    public MeetingRoom save(MeetingRoom meetingRoom) {
        return this.saveMeetingRoom(meetingRoom);
    }

    /** 
     * {@inheritDoc}
    */
    public MeetingRoom loadMeetingRoomByName(String name)  throws Exception {
        List meetingRooms = getHibernateTemplate().find("from MeetingRoom where name=?", name);
        if (meetingRooms == null || meetingRooms.isEmpty()) {
            throw new Exception("meeting room '" + name + "' not found...");
        } else {
            return (MeetingRoom) meetingRooms.get(0);
        }
    }

}
